package com.tangtang.basic.threads;

import java.util.concurrent.atomic.AtomicInteger;

public class Demo2CAS {
    private AtomicInteger i = new AtomicInteger(0);

    public static void main(String[] args) {
        Demo2CAS demo1 = new Demo2CAS();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    System.out.println(Thread.currentThread().getName());
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    demo1.add();
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {

                for (int i = 0; i < 10; i++) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    demo1.add();
                }
            }
        }).start();

    }

    public void add() {

        i.getAndAdd(1);
        System.out.println(Thread.currentThread().getName() + "->" + i);
    }


}
